/**
 * $Id: LoginUrlEntryPoint.java 74 2011-10-21 13:38:54Z feigme@gmail.com $
 */
package com.iary.interfaces.security;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.iary.interfaces.Constants;

public class LoginUrlEntryPoint implements AuthenticationEntryPoint {

	private String loginUrl;

	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authentication)
			throws IOException, ServletException {
		String targetUrl = request.getScheme()
				+ "://"
				+ request.getServerName()
				+ request.getRequestURI()
				+ (request.getQueryString() == null ? "" : "?"
						+ request.getQueryString());

		response.sendRedirect(request.getContextPath() + getLoginUrl()
				+ "?from=" + URLEncoder.encode(targetUrl, Constants.PAGE_CODE));

	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

}
